package io.renren.modules.wms.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import io.renren.common.utils.Constant;
import io.renren.modules.wms.dao.WmsSpecialMapper;
import io.renren.modules.wms.entity.WmsSpecial;
import io.renren.modules.wms.mapper.WmsCompareMapper;
import io.renren.modules.wms.vo.WmsCompare;
import io.renren.modules.wms.dao.JDEMapper;
import io.renren.modules.wms.dao.WmsDataDao;
import io.renren.modules.wms.entity.Product;
import io.renren.modules.wms.entity.WmsDataEntity;
import org.apache.http.util.TextUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * WMS 库存拉通比较程序
 *
 * @author SuperDc
 */
@Service
public class StockCompare {

    @Resource
    private WmsDataDao wmsDataDao;

    @Resource
    private JDEMapper jdeMapper;

    @Resource
    private WmsCompareMapper wmsCompareMapper;

    @Resource
    private WmsSpecialMapper wmsSpecialMapper;

    public void handle() {

        // 用来存储所有的 key = 产品代码 + 批号
        Map<String, String> allKeyMap = new HashMap<>();

        // 汇总数据集合
        Map<String, WmsDataEntity> manualJdeMap = new HashMap<>();
        Map<String, WmsDataEntity> manualFLWmsMap = new HashMap<>();
        Map<String, WmsDataEntity> manualGYWmsMap = new HashMap<>();
        Map<String, WmsDataEntity> autoJdeMap = new HashMap<>();
        Map<String, WmsDataEntity> autoFLWmsMap = new HashMap<>();
        Map<String, WmsDataEntity> autoGYWmsMap = new HashMap<>();
        Map<String, WmsDataEntity> outWmsMap = new HashMap<>();
        Map<String, WmsDataEntity> outJdeMap = new HashMap<>();
        Map<String, WmsDataEntity> kwfJdeMap = new HashMap<>();
        Map<String, WmsSpecial> specialMap = new HashMap<>();

        // 特殊账务处理
        List<WmsSpecial> wmsSpecialList =  wmsSpecialMapper.selectList(new QueryWrapper<>());
        if (!CollectionUtils.isEmpty(wmsSpecialList)){
            wmsSpecialList.forEach(item -> {
                specialMap.put(item.getCode() + item.getBatch(), item);
            });
        }

        // -----------------------------------------1------------------------------------------
        System.out.println("开始处理JDE数据");
        extracted(Constant.FROM_DB.JDE_MANUAL, allKeyMap, manualJdeMap);

        System.out.println("开始处理人工富勒数据");
        extracted(Constant.FROM_DB.FULE_MANUAL, allKeyMap, manualFLWmsMap);

        System.out.println("开始处理人工刚玉数据");
        extracted(Constant.FROM_DB.GANGYU_MANUAL, allKeyMap, manualGYWmsMap);

        System.out.println("处理自动抓取的JDE数据");
        extracted(Constant.FROM_DB.JDE_CAPTURE, allKeyMap, autoJdeMap);

        System.out.println("处理自动抓取的富勒WMS数据");
        extracted(Constant.FROM_DB.FULE_CAPTURE, allKeyMap, autoFLWmsMap);

        System.out.println("处理自动抓取的刚玉WMS数据");
        extracted(Constant.FROM_DB.GANGYU_CAPTURE, allKeyMap, autoGYWmsMap);

        System.out.println("处理自动抓取的外部JDE数据");
        extracted(Constant.FROM_DB.JDE_CAPTURE_OUT, allKeyMap, outJdeMap);

        System.out.println("处理自动抓取的外部WMS数据");
        extracted(Constant.FROM_DB.WMS_CAPTURE_OUT, allKeyMap, outWmsMap);

        System.out.println("处理开未发数据");
        extracted(Constant.FROM_DB.JDE_CAPTURE_KWF, allKeyMap, kwfJdeMap);
        // -----------------------------------------1------------------------------------------

        Map<String, Product> productMap = new HashMap<>();
        List<Product> productList = jdeMapper.selectAllProduct();
        productList.forEach(item -> productMap.put(item.getGOODID(), item));

        // -----------------------------------------2------------------------------------------
        System.out.println("比对九部分数据");
        List<WmsCompare> compareResults = new ArrayList<>();
        for (String key : allKeyMap.keySet()) {
            // 根据 key 找到对应商品的描述
            String[] array = key.split("-");
            String goodsId = array.length > 0 ? array[0] : "";
            String batchNo = array.length > 1 ? array[1] : "";
            // 批号为空和商品为空的过滤掉
            if (TextUtils.isBlank(batchNo) || TextUtils.isBlank(goodsId)) {
                continue;
            }
            // 校验商品代码是否存在
            Product product = productMap.get(goodsId);
            if (product == null) {
                continue;
            }

            WmsDataEntity autoJde = autoJdeMap.get(key);
            WmsDataEntity autoFLWms = autoFLWmsMap.get(key);
            WmsDataEntity autoGYWms = autoGYWmsMap.get(key);
            WmsDataEntity manualJde = manualJdeMap.get(key);
            WmsDataEntity manualFLWms = manualFLWmsMap.get(key);
            WmsDataEntity manualGYWms = manualGYWmsMap.get(key);
            WmsDataEntity outWms = outWmsMap.get(key);
            WmsDataEntity outJde = outJdeMap.get(key);
            WmsDataEntity kwfJde = kwfJdeMap.get(key);

            // 构建比对完成类
            WmsCompare result = new WmsCompare();
            result.setCode(goodsId);
            result.setBatch(batchNo);
            result.setName(product.getGOODSNAME());
            result.setSpec(product.getPACK());
            result.setUpdateTime(new Date());

            result.setJdeReport(manualJde == null ? "0" : manualJde.getNumNow());
            result.setJdeCapture(autoJde == null ? "0" : autoJde.getNumNow());
            result.setJdeOutCapture(outJde == null ? "0" : outJde.getNumNow());
            result.setJdeKwfNum(kwfJde == null ? "0" : kwfJde.getNumNow());

            result.setWmsGyReport(manualGYWms == null ? "0" : manualGYWms.getNumNow());
            result.setWmsFlReport(manualFLWms == null ? "0" : manualFLWms.getNumNow());
            result.setWmsReport(new BigDecimal(result.getWmsGyReport())
                    .add(new BigDecimal(result.getWmsFlReport()))
                    .toString());

            result.setWmsGyCapture(autoGYWms == null ? "0" : autoGYWms.getNumNow());
            result.setWmsFlCapture(autoFLWms == null ? "0" : autoFLWms.getNumNow());
            result.setWmsCapture(new BigDecimal(result.getWmsGyCapture())
                    .add(new BigDecimal(result.getWmsFlCapture()))
                    .toString());

            result.setWmsOutCapture(outWms == null ? "0" : outWms.getNumNow());

            // 匹配特殊账号代码
            WmsSpecial wmsSpecial = specialMap.get(result.getCode() + result.getBatch());
            if (wmsSpecial != null){
                result.setValue1(wmsSpecial.getAttr1());
                result.setValue2(wmsSpecial.getAttr2());
                result.setValue3(wmsSpecial.getNum());
                result.setValue4(wmsSpecial.getUnit());
            }

            boolean isAdd = result.getJdeReport().equals("0")
                    && result.getJdeCapture().equals("0")
                    && result.getJdeOutCapture().equals("0")
                    && result.getWmsGyReport().equals("0")
                    && result.getWmsFlReport().equals("0")
                    && result.getWmsReport().equals("0")
                    && result.getWmsGyCapture().equals("0")
                    && result.getWmsFlCapture().equals("0")
                    && result.getWmsCapture().equals("0")
                    && result.getWmsOutCapture().equals("0");

            if (!isAdd) {
                compareResults.add(result);
            }
        }

        // 过滤只有开未发的数据

        // 清空结果表
        wmsCompareMapper.delete(new QueryWrapper<>());

        // 批量插入结果
        Lists.partition(compareResults, 500).forEach(wmsCompareMapper::batchInsert);
    }

    private void extracted(String type, Map<String, String> allKeyMap, Map<String, WmsDataEntity> manualJdeMap) {
        List<WmsDataEntity> manualJdeDataList = wmsDataDao.selectList(new QueryWrapper<WmsDataEntity>()
                .eq("from_db", type));
        System.out.println(manualJdeDataList == null ? type + "数据为0" : (type + manualJdeDataList.size()));
        sumProduct(allKeyMap, manualJdeDataList, manualJdeMap);
    }

    /**
     * 相同 ID + 批号 的数据相加
     *
     * @param allKeyMap /
     * @param dataList  /
     * @param dataMap   /
     */
    private void sumProduct(Map<String, String> allKeyMap, List<WmsDataEntity> dataList, Map<String, WmsDataEntity> dataMap) {
        if (CollectionUtils.isEmpty(dataList)){
            return;
        }
        WmsDataEntity productTemp;
        for (WmsDataEntity product : dataList) {
            if (product == null) {
                continue;
            }
            String key = product.getCode().replace(" ", "") + "-" + product.getBatch().replace(" ", "");
            if (dataMap.containsKey(key)) {
                productTemp = dataMap.get(key);
                if (TextUtils.isBlank(productTemp.getNumNow())) {
                    productTemp.setNumNow("0");
                }
                if (TextUtils.isBlank(product.getNumNow())) {
                    product.setNumNow("0");
                }
                productTemp.setNumNow(new BigDecimal(productTemp.getNumNow()).add(new BigDecimal(product.getNumNow())).toString());
                dataMap.put(key, productTemp);
            } else {
                dataMap.put(key, product);
            }

            allKeyMap.put(key, key);
        }
    }

    private long getInt(String num) {
        try {
            return Math.round(Double.parseDouble(num.trim()));
        } catch (Exception e) {
            return 0;
        }
    }

}
